package com.payment.ktb.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.dialog.CustomBaseDialog;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.DeviceUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.LogUtil;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/2.
 */
public class LoginActivity extends BaseActivity {


    public static final int REQUEST_WRITE_EXTERNAL_STORAGE_CODE = 1;
    public static final int REQUEST_READ_EXTERNAL_STORAGE_CODE = 2;
    public static final int REQUEST_CAMERA_CODE = 3;


    @BindView(R.id.et_login_username)
    EditText et_login_username;
    @BindView(R.id.et_login_password)
    EditText et_login_password;
    @BindView(R.id.iv_login_save_password)
    ImageView iv_login_save_password;


    boolean passIsHide = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initData();
        //UpdateAPKUtils.updateCheck(mContext);
//        checkKTBPermissions();
    }


    /**
     *
      */
    private void initData() {
        et_login_username.setText(SharedPreferencesUtils.getString("loginName",""));
        et_login_password.setText(SharedPreferencesUtils.getString("password",""));
        if (SharedPreferencesUtils.getBoolean("save",true)){
            iv_login_save_password.setImageResource(R.mipmap.login_check);
        }else {
            iv_login_save_password.setImageResource(R.mipmap.login_unchecked);
        }
    }


    @OnClick({R.id.btn_login_login,R.id.tv_login_forget_password,R.id.tv_login_register,R.id.rl_loginname_savepassword,R.id.rl_login_dismiss})
    void click(View view){

        switch (view.getId()) {

            //is savepassword
            case R.id.rl_loginname_savepassword:
                if (SharedPreferencesUtils.getBoolean("save",true)) {
                    SharedPreferencesUtils.putBoolean("save",false);
                    iv_login_save_password.setImageResource(R.mipmap.login_unchecked);
                } else {
                    SharedPreferencesUtils.putBoolean("save",true);
                    iv_login_save_password.setImageResource(R.mipmap.login_check);
                }
                break;

            //登录
            case R.id.btn_login_login:
                if (SharedPreferencesUtils.getBoolean("save",true)) {
                    SharedPreferencesUtils.putString("password", et_login_password.getText().toString().trim());
                } else {
                    SharedPreferencesUtils.putString("password", "");
                }
                SharedPreferencesUtils.putString("loginName",et_login_username.getText().toString().trim());
                if (checkPass()) {
                    login();
                }

                break;


            //忘记密码
            case R.id.tv_login_forget_password:
                startActivity(ForgetPasswordActivity.class);
                break;

            //注册
            case R.id.tv_login_register:

                startActivity(RegisterActivity.class);

                break;

            //取消登陆
            case R.id.rl_login_dismiss:

                if (SharedPreferencesUtils.getBoolean("save",true)) {
                    SharedPreferencesUtils.putString("password", et_login_password.getText().toString().trim());
                } else {
                    SharedPreferencesUtils.putString("password", "");
                }

                if (!TextUtils.isEmpty(getIntent().getStringExtra("fromActivity")) && getIntent().getStringExtra("fromActivity").equals("SettingActivity")) {
                    startActivity(MainActivity.class);
                }else {
                    finish();
                }
                overridePendingTransition(0,R.anim.activity_close);
                break;

        }

    }


    /**
     * 检测授权
     */
    private void checkKTBPermissions() {

        check_WRITE_EXTERNAL_STORAGE_Permission();
        check_READ_EXTERNAL_STORAGE_Permission();
        check_CAMERA_Permission();

    }


    /**
     * 写入存储授权
     */
    private void check_WRITE_EXTERNAL_STORAGE_Permission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_CODE);
        } else
        {

        }
    }

    /**
     * 读取存储授权
     */
    private void check_READ_EXTERNAL_STORAGE_Permission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE_CODE);
        } else
        {

        }
    }

    /**
     * 拍照授权
     */
    private void check_CAMERA_Permission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_CODE);
        } else
        {

        }
    }

    /**
     *
     */
    private boolean checkPass() {

        if (TextUtils.isEmpty(et_login_username.getText().toString())) {
            ToastUtils.showToast("请输入用户名");
            return false;
        }

        if (et_login_username.getText().toString().length() != 11) {
            ToastUtils.showToast("请输入正确手机号码");
            return false;
        }
        if (TextUtils.isEmpty(et_login_password.getText().toString())) {
            ToastUtils.showToast("请输入密码");
            return false;
        }
            return true;
    }

    /**
     * 登录
     */
    private void login() {

        progressDialogUtils.showProgress();
        //构造传输参数
        final String phone = et_login_username.getText().toString().trim();
        String pass = et_login_password.getText().toString().trim();

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("phone",phone);
        map.put("pass",pass);
        map.put("os","ANDROID");
        map.put("soft","JNSH");
        map.put("version", "V" + DeviceUtils.getVersionName());


        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserLoginState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                        SharedPreferencesUtils.putString(ConstantsUser.userToken,jsonObject.optString("userToken"));
                        SharedPreferencesUtils.putString(ConstantsUser.userKey,jsonObject.optString("userKey"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardOrderMin,jsonObject.optString("nocardOrderMin"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardOrderMax,jsonObject.optString("nocardOrderMax"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardOrderEnd,jsonObject.optString("nocardOrderEnd"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardOrderStart,jsonObject.optString("nocardOrderStart"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardMcgMin,jsonObject.optString("nocardMcgMin"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardMcgMax,jsonObject.optString("nocardMcgMax"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardMcgStart,jsonObject.optString("nocardMcgStart"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardMcgEnd,jsonObject.optString("nocardMcgEnd"));
                        SharedPreferencesUtils.putString(ConstantsPay.nocardMcgEnd,jsonObject.optString("nocardMcgEnd"));
                        SharedPreferencesUtils.putString(ConstantsPay.T0,jsonObject.optString("T0"));
                        SharedPreferencesUtils.putString(ConstantsPay.T1,jsonObject.optString("T1"));
                        SharedPreferencesUtils.putString(ConstantsPay.T0Tip,jsonObject.optString("T0Tip"));
                        SharedPreferencesUtils.putString(ConstantsPay.T1Tip,jsonObject.optString("T1Tip"));
                        SharedPreferencesUtils.putString(ConstantsPay.T0Mcg,jsonObject.optString("T0Mcg"));
                        SharedPreferencesUtils.putString(ConstantsPay.T1Mcg,jsonObject.optString("T1Mcg"));
                        SharedPreferencesUtils.putString(ConstantsPay.noticeText,jsonObject.optString("noticeText"));
                        SharedPreferencesUtils.putString(ConstantsPay.noticeFlg,jsonObject.optString("noticeFlg"));
                        SharedPreferencesUtils.putString(ConstantsPay.noticetimes,"0");
                        SharedPreferencesUtils.putString(ConstantsPay.shopName,jsonObject.optString("shopName"));
                        SharedPreferencesUtils.putString(ConstantsPay.PHOTOGRAPHFEE,jsonObject.optString("vipPrice"));
                        ConstantsUser.userName = et_login_username.getText().toString().trim();
                        SharedPreferencesUtils.putString(ConstantsUser.phone,phone);
                        startActivity(MainActivity.class);
                        overridePendingTransition(0,R.anim.activity_close);
                        SharedPreferencesUtils.putString("logintime","上次登陆时间：" + new SimpleDateFormat("yyyy-MM-dd   HH:mm:ss").format(new Date()));
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();

               if (volleyError.getMessage().contains("html")) {


                   CustomBaseDialog dialog = new CustomBaseDialog(mContext,volleyError.getMessage());
                   dialog.show();

               }else {
                   AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());

               }


            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {


        if (grantResults != null && grantResults.length > 0) {

            for (int i = 0; i <grantResults.length ; i++) {

                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    finish();
                }
            }

        }


    }
}
